package com.jams.goodox.activity.common;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.mine.image.Util;
import com.jams.goodox.listen.CustomShareListener;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.ByteArrayOutputStream;

/**
 * Created by GJJ on 2017/8/31.
 * Description 通用加载Url的WebView
 */
public class SimpleHtmlActivity extends BaseActivity implements WbShareCallback  {

    public final static String TITLE = "title";
    public final static String URL = "url";

    private WebView webView;
    private ProgressBar progressBar;
    private String title;
    private String url;
    // IWXAPI 是第三方app和微信通信的openapi接口
    WXWebpageObject webpage;
    WXMediaMessage msg;
    SendMessageToWX.Req req;


    @Override
    protected int getLayoutId() {
        return R.layout.web_view;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    @Override
    protected void init() {
        title = getIntent().getStringExtra(TITLE);
        url = getIntent().getStringExtra(URL);
        //StyleUtil.titleBackKey(this, title);
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部

        StyleUtil.titleBothIconListener(this, title, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                },

                R.mipmap.icon_share_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        showSharePop(new CustomShareListener() {
                            @Override
                            public void onShareCallBack(int type) {

                                switch (type){
                                    case 1:

                                       /* webpage = new WXWebpageObject();
                                        webpage.webpageUrl = url;
                                        msg = new WXMediaMessage(webpage);
                                        msg.title = title;
                                        msg.description = "";

                                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
                                        msg.setThumbImage(bitmap);

                                        req = new SendMessageToWX.Req();
                                        req.transaction = buildTransaction("webpage");
                                        req.message = msg;
                                        req.scene = SendMessageToWX.Req.WXSceneSession;
                                        api.sendReq(req);*/

                                        Log.d("TTTTTT11","title = " + title);
                                        WXWebpageObject webpage = new WXWebpageObject();
                                        webpage.webpageUrl = url;
                                        WXMediaMessage msg = new WXMediaMessage(webpage);
                                        msg.title = (title == null) ? "好氧APP" : title;
                                        msg.description = /*(title == null) ? "好氧APP" : title*/" ";
                                        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
                                        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                                        bmp.recycle();
                                        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

                                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                                        req.transaction = buildTransaction("webpage");
                                        req.message = msg;
                                        req.scene = SendMessageToWX.Req.WXSceneSession;;
                                        api.sendReq(req);

                                        break;
                                    case 2:
                                        Log.d("TTTTTT11","title = " + title);
                                        webpage = new WXWebpageObject();
                                        webpage.webpageUrl = url;
                                        msg = new WXMediaMessage(webpage);
                                        msg.title = (title == null) ? "好氧APP" : title;
                                        msg.description = /*(title == null) ? "好氧APP" : title*/" ";

//                                        Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
//                                        msg.setThumbImage(bitmap2);
                                        Bitmap bmp2 = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
                                        Bitmap bitmap2 = Bitmap.createScaledBitmap(bmp2, THUMB_SIZE, THUMB_SIZE, true);
                                        bmp2.recycle();
                                        msg.thumbData = Util.bmpToByteArray(bitmap2, true);

                                        req = new SendMessageToWX.Req();
                                        req.transaction = buildTransaction("webpage");
                                        req.message = msg;
                                        req.scene = SendMessageToWX.Req.WXSceneTimeline;
                                        api.sendReq(req);
                                        break;

                                    case 3:
                                        WbShareHandler shareHandler = new WbShareHandler(SimpleHtmlActivity.this);
                                        shareHandler.registerApp();
                                        shareHandler.setProgressColor(getResources().getColor(R.color.main_background));

                                        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                                        weiboMessage.textObject = getTextObj();

                                        shareHandler.shareMessage(weiboMessage, true);

//                                        WeiboPageUtils.getInstance(SimpleHtmlActivity.this,authInfo).shareToWeibo("哈哈哈哈哈",useWeb);
                                        break;

                                    case 4:
                                        ClipboardManager cm = (ClipboardManager)
                                                getSystemService(Context.CLIPBOARD_SERVICE);
                                        // 将文本内容放到系统剪贴板里。
                                        cm.setText(url);
                                        ToastUtil.show("复制成功");
                                        break;
                                    default:
                                        break;
                                }
                            }

                        });

                    }
                });

        //StyleUtil.titleBackKey(this, title == null ? "" : title);

        webView = (WebView) findViewById(R.id.webView);
        progressBar = (ProgressBar) findViewById(R.id.progress_simple_h5);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    webView.loadUrl(url);
                    return false;
                } else {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        // 防止没有安装应用
                        e.printStackTrace();
                    }
                    return true;
                }
            }
        });

        webView.loadUrl(TextUtils.isEmpty(url) ? "" : url);

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    if (View.GONE == progressBar.getVisibility()) {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    progressBar.setProgress(newProgress);//设置进度值
                }
                super.onProgressChanged(webView, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
                if (TextUtils.isEmpty(title)) {
                    title = s;
                    StyleUtil.titleBackKey(SimpleHtmlActivity.this, s);
                }
            }
        });
    }


    /**
     * 创建文本消息对象。
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        Log.d("TTTTTT22","title = " + title);
        TextObject textObject = new TextObject();
        textObject.text = (TextUtils.isEmpty(title) ? "好氧APP" : title)  + ("  " + url);
        textObject.title = TextUtils.isEmpty(title) ? "好氧APP" : title ;
        textObject.actionUrl = url;

//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//        textObject.thumbData = baos.toByteArray();


        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.login_logo_icon);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        textObject.thumbData = Util.bmpToByteArray(thumbBmp, true);

        return textObject;
    }


    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }


    @Override
    public void onWbShareSuccess() {
        ToastUtil.show("分享成功！");
    }

    @Override
    public void onWbShareCancel() {
        ToastUtil.show("取消分享！");
    }

    @Override
    public void onWbShareFail() {
        ToastUtil.show("分享失败！");
    }


}